package com.coflxl.web.api.common.service.impl;

import com.coflxl.web.api.common.model.SysCommonSql;
import com.coflxl.web.api.common.model.dto.ApiPage;
import com.coflxl.web.api.common.model.dto.SysCommonSearchPageDTO;
import com.coflxl.web.api.common.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.model.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommonServiceImpl implements CommonService {

    @Autowired
    private DynamicQueryExecutor dynamicQueryExecutor;
    @Autowired
    private SqlToyLazyDao sqlToyLazyDao;

    @Override
    public List search(String key, Map paramMap) throws Exception {
        return dynamicQueryExecutor.executeListQuery(key, paramMap);
    }
    @Override
    public Map searchByOne(String key, Map paramMap) throws Exception {
        return dynamicQueryExecutor.executeSingleQuery(key, paramMap);
    }
    @Override
    public ApiPage<Map> searchPage(String key, SysCommonSearchPageDTO pageDto) throws Exception {
        Page<Map> page = dynamicQueryExecutor.executePageQuery(key, pageDto, pageDto.getMap());
        return ApiPage.rest(page);
    }

    @Override
    public Long addKey(String key, Map<String, Object> paramMap) throws Exception {

        return dynamicQueryExecutor.executeSingleAdd(key, paramMap);
    }

    @Override
    public String saveOrUpdate(String table, Map<String, Object> paramMap) {
        try {
            // 假设实体类都在 com.example.model 包下
            //TODO  需要增加一个配置，用于获取table 对应的实体是在哪个包下
            String entityClassName = "com.coflxl.web.api.user.model." + toCamelCase(table, true);
            Class<?> clazz = Class.forName(entityClassName);
            // 检查是否实现 Serializable 接口
            if (!Serializable.class.isAssignableFrom(clazz)) {
                throw new IllegalArgumentException("实体类未实现 Serializable 接口：" + entityClassName);
            }
            // 创建实体对象，并强制转换为 Serializable
            Serializable entity = (Serializable) clazz.getDeclaredConstructor().newInstance();
            // 将 paramMap 中的值注入到实体字段
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                String fieldName = entry.getKey();
                Object value = entry.getValue();
                try {
                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    field.set(entity, value);
                } catch (NoSuchFieldException e) {
                    // 字段不存在就跳过，也可以打印日志
                }
            }
            // 保存或更新
            return sqlToyLazyDao.saveOrUpdate(entity) + "";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail: " + e.getMessage();
        }
    }

    // 工具方法：user_table -> UserTable
    private String toCamelCase(String table, boolean capitalizeFirst) {
        StringBuilder result = new StringBuilder();
        for (String part : table.split("_")) {
            if (part.isEmpty()) continue;
            result.append(Character.toUpperCase(part.charAt(0)))
                    .append(part.substring(1).toLowerCase());
        }
        if (!capitalizeFirst && result.length() > 0) {
            result.setCharAt(0, Character.toLowerCase(result.charAt(0)));
        }
        return result.toString();
    }
}